package collection.list;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * 根据对象的某个属性去重
 */
public class DistinctByProperties {

    public static void main(String[] args) {
        // 创建几个param对象
        param param1 = new param("a", 1);
        param param2 = new param("b", 2);
        param param3 = new param("c", 3);
        param param4 = new param("a", 1);
        param param5 = new param("b", 2);
        param param6 = new param("c", 3);
        param param7 = new param("d", 3);
        // 创建一个list集合
        List<param> list = new ArrayList<>();
        list.add(param1);
        list.add(param2);
        list.add(param3);
        list.add(param4);
        list.add(param5);
        list.add(param6);
        list.add(param7);
        // 去重
        List<param> distinctList = list.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(param::getId))),
                        ArrayList::new));

        System.out.println(JSON.toJSONString(distinctList));

    }

    static class param {

        String name;

        Integer id;

        public param(String name, Integer id) {
            this.name = name;
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }
    }

}
